package org.cars.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.cars.netty.client.handler.FirstClientHandler;
import org.cars.netty.client.handler.HeartBeatHandler;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Scanner;

import static org.cars.decoder.StringLineDelimiterDecoder.SEPARATOR;

/**
 * @author 闪电侠
 */
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();

        bootstrap
                // 1.指定线程模型
                .group(group)
                // 2.指定 IO 类型为 NIO
                .channel(NioSocketChannel.class)
                // 3.添加自定义handler
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline()
                                .addLast(new StringEncoder())
                                .addLast(new IdleStateHandler(5, 0, 0))
                                .addLast(new HeartBeatHandler())
                                .addLast(new FirstClientHandler());
                    }
                });

        // 4.建立连接
        Channel channel = bootstrap.connect("127.0.0.1", 8000).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("连接成功!");
            } else {
                System.out.println("连接失败!");
            }
        }).channel();

        //5. 通过控制台手动输入数据
        Scanner scanner = new Scanner(System.in);

        while (true) {
            //手动输入数据
            String message = scanner.nextLine();
            byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
            ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(messageBytes.length + 1);
            buffer.writeBytes(messageBytes);
            //在数据的最后写一个 \n 作为分隔符
            buffer.writeByte(SEPARATOR);
            channel.writeAndFlush(buffer);

            channel.writeAndFlush(new Date() + ": hello world!");
            Thread.sleep(2000);
        }
    }
}